<template>
  <div class="app-container">
    <div class="search-area" v-show="showSearch">
      <el-form
        :model="queryParams"
        @submit.native.prevent
        ref="queryForm"
        size="small"
        :inline="true"
        class="clearfix"
        label-width="auto"
      >
        <el-form-item label="审批模板名称" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入审批模板名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="main-content">
      <el-row :gutter="10" class="mb24">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['biz:approval:template:add']"
            >新增</el-button
          >
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
      </el-row>
      <el-table v-loading="loading" :data="templateList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="审批模板code" align="center" prop="processCode" v-if="columns.processCode.visible" />
        <el-table-column label="审批模板名称" align="center" prop="name" v-if="columns.name.visible" />
        <el-table-column label="模板描述" align="center" prop="description" v-if="columns.description.visible" />
        <!-- <el-table-column
          label="审批模板组件配置"
          align="center"
          prop="componentConfig"
          v-if="columns.componentConfig.visible"
        /> -->
        <!-- <el-table-column label="审批人配置" align="center" prop="approver" v-if="columns.approver.visible" /> -->
        <el-table-column label="是否为静态模板" align="center" prop="isStatic" v-if="columns.isStatic.visible">
          <template slot-scope="scope">
            {{ scope.row.isStatic == 1 ? '是' : '否' }}
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" v-if="columns.createTime.visible" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-tickets"
              @click="handleUpdate(scope.row, true)"
              v-hasPermi="['biz:approval:template:getInfo']"
              >查看</el-button
            >
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['biz:approval:template:edit']"
              >修改</el-button
            >
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['biz:approval:template:remove']"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <!-- 添加或修改审批模板配置对话框 -->
    <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="open" width="850px" append-to-body>
      <el-form
        ref="form"
        :model="form"
        label-width="auto"
        :rules="rules"
        :disabled="disabled"
        :class="{ 'detail-disabled': disabled }"
      >
        <el-form-item label="是否为静态模板" prop="isStatic">
          <el-select v-model="form.isStatic" placeholder="请选择是否为静态模板">
            <el-option key="1" label="是" :value="1"> </el-option>
            <el-option key="0" label="否" :value="0"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="审批模板code"
          v-if="form.isStatic == 1 || form.processCode"
          prop="processCode"
          :rules="{
            required: form.isStatic == 1 || form.processCode,
            message: '审批模板code不能为空',
            trigger: 'blur',
          }"
        >
          <el-input v-model="form.processCode" placeholder="请输入审批模板code" />
        </el-form-item>
        <el-form-item label="审批模板名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入审批模板名称" />
        </el-form-item>
        <template v-if="form.isStatic === 0">
          <el-divider content-position="center">审批人配置</el-divider>
          <el-row>
            <el-col :span="20">
              <el-form-item
                label-width="0px"
                style="margin-bottom: 0px"
                label
                v-for="(domain, index) in form.approver"
                :key="domain.curentKey"
              >
                <el-form-item
                  :label="`审批类型${index + 1}`"
                  :prop="'approver.' + index + '.actionType'"
                  :rules="{
                    required: true,
                    message: '请选择审批类型',
                    trigger: 'change',
                  }"
                >
                  <el-col :span="10">
                    <el-select
                      v-model="domain.actionType"
                      placeholder="请选择审批类型"
                      @change="
                        () => {
                          domain.userIds = []
                        }
                      "
                    >
                      <el-option key="AND" label="会签" value="AND"> </el-option>
                      <el-option key="OR" label="或签" value="OR"> </el-option>
                      <el-option key="NONE" label="单人审批" value="NONE"> </el-option>
                    </el-select>
                  </el-col>
                </el-form-item>
                <el-form-item
                  :label="`审批人${index + 1}`"
                  :prop="'approver.' + index + '.userIds'"
                  :rules="{
                    required: true,
                    message: '请选择钉钉用户',
                    trigger: 'change',
                  }"
                >
                  <el-col :span="20">
                    <el-select
                      v-model="domain.userIds"
                      multiple
                      :disabled="!domain.actionType"
                      :multiple-limit="domain.actionType == 'OR' || domain.actionType == 'AND' ? 20 : 1"
                      filterable
                      remote
                      reserve-keyword
                      placeholder="输入关键词，可获取更多用户"
                      :remote-method="getDingTalkList"
                      :loading="dingTalkListLoading"
                      @change="
                        (val) => {
                          dingTalkChange(val, domain)
                          domain.userIds = val
                        }
                      "
                    >
                      <el-option
                        v-for="item in dingTalkList"
                        :key="`ding_${item.userId}`"
                        :label="item.dingTalkUserName"
                        :value="item.dingTalkUserId"
                      >
                      </el-option>
                    </el-select>
                  </el-col>
                  <el-col :span="1">⠀</el-col>
                  <el-col :span="3">
                    <el-button @click.prevent="removeDomain(domain, 'approver')">删除</el-button>
                  </el-col>
                </el-form-item>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item>
            <el-button type="primary" @click="addDomain('approver')">添加新审批人</el-button>
          </el-form-item>
        </template>

        <template>
          <el-divider content-position="center">审批模板组件配置</el-divider>
          <el-form-item
            label-width="0px"
            style="margin-bottom: 0px"
            label
            v-for="(domain, index) in form.componentConfig"
            :key="domain.curentKey"
          >
            <el-form-item
              :label="`表单控件类型${index + 1}`"
              :prop="'componentConfig.' + index + '.componentType'"
              :rules="{
                required: true,
                message: '请选择表单控件类型',
                trigger: 'change',
              }"
            >
              <el-col :span="10">
                <el-select v-model="domain.componentType" placeholder="请选择表单控件类型">
                  <el-option v-for="item in componentType" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-col>
            </el-form-item>
            <el-form-item
              :label="`key${index + 1}`"
              :prop="'componentConfig.' + index + '.key'"
              :rules="{
                required: true,
                message: '请输入key',
                trigger: 'blur',
              }"
            >
              <el-col :span="10">
                <el-input v-model="domain.key" placeholder="属性key，对应后续发送审批时的参数" />
              </el-col>
            </el-form-item>
            <el-form-item
              :label="`label${index + 1}`"
              :prop="'componentConfig.' + index + '.label'"
              :rules="{
                required: true,
                message: '请输入label',
                trigger: 'change',
              }"
            >
              <el-col :span="20">
                <el-input
                  v-model="domain.label"
                  placeholder='注意，控件类型为时间区间控件时，需参考格式：["开始时间","结束时间"]'
                />
              </el-col>
            </el-form-item>
            <el-form-item
              v-if="['DDMultiSelectField', 'DDSelectField'].indexOf(domain.componentType) > -1"
              :label="`optionList${index + 1}`"
              :prop="'componentConfig.' + index + '.optionList'"
              :rules="{
                required: true,
                message: '请输入optionList',
                trigger: 'blur',
              }"
            >
              <el-col :span="20">
                <el-input
                  type="textarea"
                  v-model="domain.optionList"
                  placeholder='需参考格式： ["选项1","选项2","选项3"]'
                />
              </el-col>
            </el-form-item>
            <el-form-item
              v-if="['NumberField', 'MoneyField', 'DDDateField', 'DDDateRangeField'].indexOf(domain.componentType) > -1"
              :label="`unit${index + 1}`"
              :prop="'componentConfig.' + index + '.unit'"
              :rules="{
                required: true,
                message: '请输入单位',
                trigger: 'blur',
              }"
            >
              <el-col :span="20">
                <el-input v-model="domain.unit" placeholder="数字控件、日期空间等需要单位类型时使用" />
              </el-col>
            </el-form-item>
            <el-form-item
              :label="`placeholder${index + 1}`"
              :prop="'componentConfig.' + index + '.placeholder'"
              :rules="{
                required: true,
                message: '请输入提示语',
                trigger: 'blur',
              }"
            >
              <el-col :span="20">
                <el-input v-model="domain.placeholder" placeholder="placeholder提示语" />
              </el-col>
            </el-form-item>
            <el-form-item :label="`required${index + 1}`" :prop="'componentConfig.' + index + '.required'">
              <el-switch v-model="domain.required" active-text="必填" inactive-text="非必填"> </el-switch>
            </el-form-item>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="addDomain('componentConfig')">添加新审批模板组件</el-button>
          </el-form-item>
        </template>
        <el-divider content-position="center"></el-divider>
        <el-form-item label="模板描述" prop="description">
          <el-input type="textarea" v-model="form.description" placeholder="请输入模板描述" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" v-if="!disabled">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listTemplate,
  getTemplate,
  delTemplate,
  addTemplate,
  updateTemplate,
  getTemplateConfigDesc,
  getDingTalkListApi,
} from '@/api/biz/approvalTemplate'

export default {
  name: 'Template',
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 审批模板配置表格数据
      templateList: [],
      // 弹出层标题
      title: '',
      // 是否禁止表单填写
      disabled: false,
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
      },
      // 表单参数
      form: {},
      // 列信息
      columns: {
        processCode: { label: '审批模板code', visible: true },
        name: { label: '审批模板名称', visible: true },
        description: { label: '模板描述', visible: true },
        formComponents: { label: '审批模板组件配置', visible: true },
        approver: { label: '审批人配置', visible: true },
        isStatic: { label: '是否为静态模板', visible: true },
        createTime: { label: '创建时间', visible: true },
      },
      // 表单校验
      rules: {
        isStatic: [{ required: true, message: '是否为静态模板不能为空', trigger: 'blur' }],
        name: [{ required: true, message: '审批模板名称不能为空', trigger: 'blur' }],
        description: [{ required: true, message: '模板描述不能为空', trigger: 'blur' }],
        formComponents: [{ required: true, message: '审批模板组件配置不能为空', trigger: 'blur' }],
        approver: [{ required: true, message: '审批人配置不能为空', trigger: 'blur' }],
      },
      componentType: [
        {
          label: '单行文本',
          value: 'TextField',
        },
        {
          label: '多行文本',
          value: 'TextareaField',
        },
        {
          label: '金额',
          value: 'MoneyField',
        },
        {
          label: '数字输入框',
          value: 'NumberField',
        },
        {
          label: '单选框',
          value: 'DDSelectField',
        },
        {
          label: '多选框',
          value: 'DDMultiSelectField',
        },
        {
          label: '日期',
          value: 'DDDateField',
        },
        {
          label: '日期区间',
          value: 'DDDateRangeField',
        },
        {
          label: '图片',
          value: 'DDPhotoField',
        },
        {
          label: '附件',
          value: 'DDAttachment',
        },
      ],
      dingTalkList: [],
      dingTalkListLoading: false,
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询审批模板配置列表 */
    getList() {
      this.loading = true
      listTemplate(this.formatParamsBatch(this.queryParams)).then((response) => {
        this.templateList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        processCode: null,
        name: null,
        description: null,
        componentConfig: [
          {
            componentType: null,
            key: null,
            label: null,
            required: false,
            placeholder: null,
          },
        ],
        approver: [
          {
            actionType: null,
            dingTalkUserDtoList: null,
          },
        ],
        isStatic: 1,
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.disabled = false
      this.title = '添加审批模板配置'
      this.open = true
      this.getDingTalkList()
    },
    /** 修改按钮操作 */
    handleUpdate(row, readOnly) {
      this.reset()
      const id = row.processCode
      getTemplate(id).then((response) => {
        const configList = JSON.parse(response.data.componentConfig)
        const userList = []
        configList.map((item) => {
          if (item.optionList) {
            item.optionList = JSON.stringify(item.optionList)
          }
        })
        response.data.componentConfig = configList
        const approverList = JSON.parse(response.data.approver)
        approverList.map((item) => {
          if (item.dingTalkUserDtoList) {
            item.dingTalkUserDtoList.map((item) => {
              const currentUserIds = userList.map((itemb) => itemb.dingTalkUserId)
              if (currentUserIds.indexOf(item.dingTalkUserId) === -1) {
                userList.push(item)
              }
            })
          }
        })
        this.dingTalkList = userList
        response.data.approver = approverList
        this.form = response.data
        this.disabled = readOnly ? true : false
        this.title = readOnly ? '审批模板配置详情' : '修改审批模板配置'
        this.open = true
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate((valid, value) => {
        if (valid) {
          const currenData = JSON.parse(JSON.stringify(this.form))
          const configList = currenData.componentConfig
          delete currenData.componentConfig
          currenData.formComponents = []
          let check = true
          configList.map((item, index) => {
            if (item.optionList) {
              try {
                const obj = JSON.parse(item.optionList)
                if (typeof obj === 'object') {
                  item.optionList = obj
                } else {
                  throw new Date()
                }
              } catch (e) {
                setTimeout(() => {
                  this.$message.error({
                    showClose: true,
                    message: `审批模板组件配置：第${index + 1}条数据，字段optionList的值格式出现错误`,
                  })
                }, 150)
                check = false
              }
            }
          })
          currenData.formComponents = configList

          let approverList = currenData.approver || []
          delete currenData.approver
          if (currenData.isStatic === 1) {
            approverList = []
          }
          currenData.approverList = approverList
          if (!check) return
          if (this.form.id != null) {
            updateTemplate(currenData).then((response) => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addTemplate(currenData).then((response) => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal
        .confirm('是否确认删除审批模板配置编号为"' + ids + '"的数据项？')
        .then(function () {
          return delTemplate(ids)
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        'biz/template/export',
        {
          ...this.queryParams,
        },
        `template_${new Date().getTime()}.xlsx`
      )
    },
    removeDomain(item, name = '') {
      var index = this.form[name].indexOf(item)
      if (index !== -1) {
        this.form[name].splice(index, 1)
      }
    },
    addDomain(name = '') {
      this.form[name].push({
        value: '',
        curentKey: Date.now(),
      })
    },
    getDingTalkList(query = '') {
      this.dingTalkListLoading = true
      getDingTalkListApi({
        keyword: query,
        pageNum: 1,
        pageSize: 10,
      })
        .then(({ rows = [] }) => {
          this.dingTalkList = rows
          this.dingTalkListLoading = false
        })
        .catch(() => {
          this.dingTalkListLoading = false
        })
    },
    dingTalkChange(userIdList = [], domain = {}) {
      const dingTalkUserDtoList = domain.dingTalkUserDtoList || []
      const filterList = this.dingTalkList.filter((item) => userIdList.indexOf(item.dingTalkUserId) > -1)
      filterList.filter((item) => {
        const index = dingTalkUserDtoList.findIndex((itema) => itema.dingTalkUserId == item.dingTalkUserId)
        if (index === -1) {
          dingTalkUserDtoList.push(item)
        }
      })
      domain.dingTalkUserDtoList = dingTalkUserDtoList.filter(item=>userIdList.indexOf(item.dingTalkUserId)>-1)
    },
  },
}
</script>
<style scoped lang="scss">
.el-date-editor,
.el-select {
  width: 100%;
}
</style>
